package com.wyj.controller;

import com.wyj.constants.AllConstants;
import com.wyj.pojo.Comment;
import com.wyj.pojo.User;
import com.wyj.service.blog.BlogService;
import com.wyj.service.comment.CommentService;
import com.wyj.util.OutInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

@Controller
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    BlogService blogService;

    @Value("${comment.avatar}")
    private String avatar;

    @Value("${comment.avatarAdmin}")
    private String avatarAdmin;

    // 通过下面函数的跳转或是页面刷新
    @GetMapping("/comments/{blogId}")
    public String comments(@PathVariable Long blogId, Model model, HttpSession session){
        model.addAttribute("commentLists", commentService.queryTopCommentsByBlogId(blogId));

//        // 判断是不是博主
//        User user = (User) session.getAttribute(AllConstants.USER_SESSION);
//        if (user != null) {
//            model.addAttribute("session", user);
//
//            OutInfo.systemOutput("Comment User ", user);
//        }
        return "blog :: commentList";
    }

    @PostMapping("/comments")
    public String postComments(Comment comment, HttpSession session){
        Long blogId = comment.getBlog().getId();
        comment.setBlog(blogService.getBlogById(blogId));
        comment.setBlogId(blogId);
        // 判断是不是博主的评论
        User user = (User) session.getAttribute(AllConstants.USER_SESSION);
        if (user != null) {
            comment.setAvatar(avatarAdmin);
            comment.setAdminComment(true);
        } else {
            //设置头像
            comment.setAvatar(avatar);
        }

//        System.out.println(" ==============Start============== ");
//        System.out.println(comment.toString());
//        System.out.println("================End==============");

        commentService.saveComment(comment);

        // 这里跳转上面的 commentsList()函数：因为地址格式对应
        return "redirect:/comments/" + blogId;
    }


}
